package com.wing.web.config;

import cn.hutool.core.util.ObjectUtil;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.google.common.base.Predicates;
import com.wing.web.annotation.AuthPass;
import io.prometheus.client.Predicate;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;

import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;

/**
 * knife4j配置
 *
 * @author
 */
@Profile({"dev","test","pro"})
@Configuration
//开启 Swagger3
@EnableOpenApi
//开启 knife4j
@EnableKnife4j
public class Knife4jConfig {
    @Bean
    public Docket createRestApi() {
        // Swagger 2 使用的是：DocumentationType.SWAGGER_2
        // Swagger 3 使用的是：DocumentationType.OAS_30
        return new Docket(DocumentationType.OAS_30)
                // 定义是否开启swagger，false为关闭，可以通过变量控制
                .enable(true)
                // 将api的元信息设置为包含在json ResourceListing响应中。
                .apiInfo(new ApiInfoBuilder()
                        .title("Knife4j接口文档")
                        // 描述
                        .description("平台服务管理api")
                        .contact(new Contact("作者", "地址", "邮箱或联系方式"))
                        .version("1.0.0")
                        .build())
                // 分组名称
                .groupName("1.0")
                // 选择哪些接口作为swagger的doc发布
                .select()
                // 要扫描的API(Controller)基础包
                // .apis(RequestHandlerSelectors.basePackage("com.wing"))
                // 指定注解的方法不需要扫描（实测无效）
                .apis(RequestHandlerSelectors.withClassAnnotation(AuthPass.class).negate())
                // springfox 3.0.0 已不支持 google 依赖
                // .apis(Predicates.not(RequestHandlerSelectors.withClassAnnotation(AuthPass.class)))
                // 指定注解的方法需要扫描
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                // 错误路径不监控
                .paths(PathSelectors.regex("/error.*").negate())
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 方案一
     * springfox处理程序提供者bean后处理器
     * 解决 Spring Boot 2.6.x版本引入依赖 springfox-boot-starter (Swagger 3.0) 后，启动容器会报错
     * Failed to start bean ‘ documentationPluginsBootstrapper ‘ ;
     *
     * @return {@link BeanPostProcessor}
     */
    // @Bean
    // public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(
    // 		WebEndpointsSupplier webEndpointsSupplier,
    // 	 	ServletEndpointsSupplier servletEndpointsSupplier,
    // 		ControllerEndpointsSupplier controllerEndpointsSupplier,
    // 	 	EndpointMediaTypes endpointMediaTypes,
    // 		CorsEndpointProperties corsProperties,
    // 		WebEndpointProperties webEndpointProperties,
    // 		Environment environment
    // ) {
    //
    // 	List<ExposableEndpoint<?>> allEndpoints = new ArrayList<>();
    // 	Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
    // 	allEndpoints.addAll(webEndpoints);
    // 	allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
    // 	allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
    // 	String basePath = webEndpointProperties.getBasePath();
    // 	EndpointMapping endpointMapping = new EndpointMapping(basePath);
    // 	boolean shouldRegisterLinksMapping =
    // 			webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath)
    // 					|| ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
    // 	return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes,
    // 			corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath),
    // 			shouldRegisterLinksMapping, null);
    // }

    /**
     * 方案二
     * springfox处理程序提供者bean后处理器
     * 解决 Spring Boot 2.6.x版本引入依赖 springfox-boot-starter (Swagger 3.0) 后，启动容器会报错
     * Failed to start bean ‘ documentationPluginsBootstrapper ‘ ;
     *
     * @return {@link BeanPostProcessor}
     */
    @Bean
    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {

            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
                    customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
                }
                return bean;
            }

            private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
                List<T> copy = mappings.stream()
                        .filter(mapping -> mapping.getPatternParser() == null)
                        .collect(Collectors.toList());
                mappings.clear();
                mappings.addAll(copy);
            }

            @SuppressWarnings("unchecked")
            private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
                try {
                    Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
                    field.setAccessible(true);
                    return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new IllegalStateException(e);
                }
            }
        };
    }

}


